import { defineStore } from 'pinia'
import { getMenu } from '@/api/menu'

// 全量引入 views 下所有 index.vue
const modules = import.meta.glob('@/views/**/index.vue')

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: []
  }),
  actions: {
    async loadMenu() {
      try {
        const res = await getMenu()
        if (res.code === 200) {
          const routes = res.data.map(item => this.transformMenuToRoute(item))
          this.routes = routes
          return routes
        }
        return []
      } catch (error) {
        console.error('Failed to load menu:', error)
        return []
      }
    },
    transformMenuToRoute(menuItem) {
      const { menu, childernMenu } = menuItem
      const hasChildren = childernMenu && childernMenu.length > 0
      const route = {
        path: menu.url || `/${menu.name}`,
        name: menu.name,
        meta: {
          title: menu.name,
          icon: 'menu'
        }
      }
      if (hasChildren) {
        route.component = () => import('@/layout/index.vue')
        route.children = childernMenu.map(child => this.transformMenuToRoute(child))
      } else {
        route.component = menu.url
          ? modules[`/src/views${menu.url}/index.vue`]
          : () => import('@/layout/index.vue')
      }
      return route
    }
  }
})

/**
 * 使用meta.roles判断当前用户是否有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  //   if (route.meta && route.meta.roles) {
  //     return roles.some(role => route.meta.roles.includes(role))
  //   } else {
  //     return true
  //   }
}

/**
 * 递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menuList: []
  }),
  actions: {
    async loadMenu() {
      const res = await getMenu()
      this.menuList = res.data // 假设接口返回 { data: [...] }
    }
  }
}) 